<template>
    <div class="art-complaint-management">
        <!-- 操作栏 -->
        <div class="operation-bar">
            <el-input
                v-model="searchText"
                placeholder="搜索投诉编号/作品编号/问题类型"
                style="width: 300px"
                clearable
            >
                <template #prefix>
                    <span style="margin-right: 8px">🎨</span>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
                <span style="margin-right: 5px">+</span>新建投诉
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredComplaints" border style="width: 100%">
            <el-table-column prop="complaintId" label="投诉编号" width="180" sortable />
            <el-table-column prop="artworkNo" label="作品编号" width="180">
                <template #default="{ row }">
                    ART-{{ row.artworkNo }}
                </template>
            </el-table-column>
            <el-table-column prop="issueType" label="问题类型" width="150">
                <template #default="{ row }">
                    <el-tag :type="typeTagType[row.issueType]">{{ row.issueType }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="submitDate" label="提交时间" width="150">
                <template #default="{ row }">
                    {{ formatDate(row.submitDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="content" label="问题描述" width="200">
                <template #default="{ row }">
                    <span v-if="row.content.length > 20">{{ row.content.slice(0, 20) }}...</span>
                    <span v-else>{{ row.content }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="处理状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="statusType[row.status]">
                        {{ statusOptions.find(s => s.value === row.status)?.label }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">处理</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row.id)">归档</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEditMode ? '处理品控投诉' : '新建投诉'"
            width="600"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
            >
                <el-form-item label="投诉编号" prop="complaintId">
                    <el-input v-model="formData.complaintId" :disabled="isEditMode" />
                </el-form-item>
                <el-form-item label="作品编号" prop="artworkNo">
                    <el-input v-model="formData.artworkNo" placeholder="YYYYMMDD+3位序列"/>
                </el-form-item>
                <el-form-item label="问题类型" prop="issueType">
                    <el-select v-model="formData.issueType" placeholder="请选择类型">
                        <el-option
                            v-for="item in issueTypes"
                            :key="item"
                            :label="item"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="提交时间" prop="submitDate">
                    <el-date-picker
                        v-model="formData.submitDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="问题描述" prop="content">
                    <el-input type="textarea" v-model="formData.content" rows="3" 
                        placeholder="请详细描述：1.具体缺陷 2.发现时间 3.相关证据"/>
                </el-form-item>
                <el-form-item label="处理状态" prop="status">
                    <el-select v-model="formData.status" placeholder="请选择状态">
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 日期格式化（包含时间）
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-')
}

// 品控问题类型（参考网页4/8的油画品控问题）
const issueTypes = [
    '颜料褪色',
    '画布开裂',
    '框架变形',
    '运输损伤',
    '涂层剥落',
    '真伪争议',
    '保存不当'
]

// 标签样式映射（艺术品质控主题）
const typeTagType = {
    '颜料褪色': 'warning',
    '画布开裂': 'danger',
    '框架变形': 'info',
    '运输损伤': 'danger',
    '涂层剥落': 'warning',
    '真伪争议': 'danger',
    '保存不当': 'primary'
}

// 处理状态选项
const statusOptions = [
    { value: 0, label: '待鉴定' },
    { value: 1, label: '处理中' },
    { value: 2, label: '已结案' }
]
const statusType = { 0: 'danger', 1: 'warning', 2: 'success' }

// 7条油画品控投诉数据（参考网页4/5/8案例）
const complaints = ref([
    {
        id: 1,
        complaintId: 'ART202406001',
        artworkNo: '20240501',
        issueType: '运输损伤',
        submitDate: '2024-06-01 09:15:00',
        content: '运输过程中画框严重变形，右上角有3cm裂痕，防撞包装缺失',
        status: 0
    },
    {
        id: 2,
        complaintId: 'ART202406002',
        artworkNo: '20240415',
        issueType: '真伪争议',
        submitDate: '2024-06-02 14:30:00',
        content: '经光谱分析发现使用现代化学颜料，与标注的19世纪创作时期不符',
        status: 1
    },
    {
        id: 3,
        complaintId: 'ART202406003',
        artworkNo: '20240320',
        issueType: '保存不当',
        submitDate: '2024-06-03 11:00:00',
        content: '仓储环境湿度超标导致画布霉变，涉及3幅印象派作品',
        status: 2
    },
    {
        id: 4,
        complaintId: 'ART202406004',
        artworkNo: '20240510',
        issueType: '涂层剥落',
        submitDate: '2024-06-04 16:45:00',
        content: '油画保护涂层出现片状剥落，影响画面整体观感',
        status: 0
    },
    {
        id: 5,
        complaintId: 'ART202406005',
        artworkNo: '20240201',
        issueType: '画布开裂',
        submitDate: '2024-06-05 10:20:00',
        content: '大型油画（150x200cm）底部出现纵向开裂，长度达15cm',
        status: 1
    },
    {
        id: 6,
        complaintId: 'ART202406006',
        artworkNo: '20240515',
        issueType: '颜料褪色',
        submitDate: '2024-06-06 15:10:00',
        content: '蓝色系颜料在紫外线照射下出现明显色差，涉及天空部分',
        status: 2
    },
    {
        id: 7,
        complaintId: 'ART202406007',
        artworkNo: '20240425',
        issueType: '框架变形',
        submitDate: '2024-06-07 13:25:00',
        content: '镀金画框在运输中挤压变形，导致画布张力失衡',
        status: 0
    }
])

// 搜索功能（支持多字段模糊搜索）
const searchText = ref('')
const filteredComplaints = computed(() => {
    const searchKey = searchText.value.toLowerCase()
    return complaints.value.filter(complaint => {
        return [
            complaint.complaintId,
            complaint.artworkNo,
            complaint.issueType,
            complaint.content
        ].join('').toLowerCase().includes(searchKey)
    })
})

// 对话框状态管理
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
    id: null,
    complaintId: '',
    artworkNo: '',
    issueType: '',
    submitDate: new Date().toISOString().split('.')[0],
    content: '',
    status: 0
})

// 表单验证规则（参考网页4/5的品控标准）
const formRules = {
    artworkNo: [
        { required: true, message: '请输入作品编号', trigger: 'blur' },
        { pattern: /^\d{8}\d{3}$/, message: '格式：8位日期+3位序列', trigger: 'blur' }
    ],
    issueType: [{ required: true, message: '请选择问题类型', trigger: 'change' }],
    submitDate: [{ required: true, message: '请选择提交时间', trigger: 'change' }],
    content: [
        { required: true, message: '请填写问题描述', trigger: 'blur' },
        { min: 10, max: 300, message: '需包含：1.缺陷详情 2.发现过程 3.影响范围' }
    ],
    status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 操作函数（参考网页5/10的处理流程）
const handleAdd = () => {
    isEditMode.value = false
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row) => {
    isEditMode.value = true
    Object.assign(formData, { ...row })
    dialogVisible.value = true
}

const handleDelete = (id) => {
    ElMessageBox.confirm('确定归档该投诉？归档后进入品控案例库', '警告', {
        confirmButtonText: '确认归档',
        cancelButtonText: '取消操作',
        type: 'warning'
    }).then(() => {
        complaints.value = complaints.value.filter(c => c.id !== id)
        ElMessage.success('投诉已归档至品控案例库')
    })
}

const submitForm = async () => {
    try {
        await formRef.value.validate()
        
        if (isEditMode.value) {
            const index = complaints.value.findIndex(c => c.id === formData.id)
            complaints.value.splice(index, 1, { ...formData })
        } else {
            // 生成新的投诉编号和作品编号
            const now = new Date()
            const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '')
            const randomNum = Math.floor(Math.random() * 900) + 100
            
            complaints.value.push({
                ...formData,
                id: Date.now(),
                submitDate: formData.submitDate || new Date().toISOString().split('.')[0],
                complaintId: `ART${dateStr}${randomNum}`,
                artworkNo: `${dateStr}${randomNum}`
            })
        }
        
        dialogVisible.value = false
        ElMessage.success(isEditMode.value ? '投诉已更新' : '新投诉已提交')
    } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单信息是否完整正确')
    }
}

const resetForm = () => {
    formData.id = null
    formData.complaintId = ''
    formData.artworkNo = ''
    formData.issueType = ''
    formData.submitDate = new Date().toISOString().split('.')[0]
    formData.content = ''
    formData.status = 0
}
</script>

<style scoped>
.art-complaint-management {
    padding: 20px;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.operation-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    border-bottom: 1px solid #e8e6e6;
    padding-bottom: 15px;
}

.el-table {
    margin-top: 20px;
    background: #ffffff;
    border: 1px solid #e8e6e6;
}

.el-tag {
    font-weight: 500;
    border-radius: 12px;
}

.el-textarea__inner {
    height: 100px;
    background: #f8f9fa;
}

.el-dialog {
    border-radius: 8px;
    border: 1px solid #d3dce6;
}

.el-form-item__label {
    color: #2c3e50;
    font-weight: 500;
}
</style>